package com.connector.server.server;

import org.slf4j.LoggerFactory;
import java.io.InputStream;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.channel.ChannelFutureListener;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.netty.buffer.ByteBuf;
import com.connector.base.config.InstantConfig;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullHttpRequest>
{
    private static final Logger log;
    
    protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
        if (!request.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, request, (FullHttpResponse)new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        if (request.method() != HttpMethod.GET) {
            sendHttpResponse(ctx, request, (FullHttpResponse)new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
            return;
        }
        if ("/".equals(request.uri()) || "/index.html".equals(request.uri())) {
            final ByteBuf content = this.getContent();
            final FullHttpResponse res = (FullHttpResponse)new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            res.headers().set((CharSequence)HttpHeaderNames.CONTENT_TYPE, (Object)"text/html; charset=UTF-8");
            HttpUtil.setContentLength((HttpMessage)res, (long)content.readableBytes());
            sendHttpResponse(ctx, request, res);
        }
        else if (InstantConfig.server.websocket.wsPath.equals(request.uri())) {
            sendHttpResponse(ctx, request, (FullHttpResponse)new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS));
        }
        else {
            sendHttpResponse(ctx, request, (FullHttpResponse)new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        }
        ctx.pipeline().remove((ChannelHandler)this);
    }
    
    private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest request, final FullHttpResponse response) {
        if (response.status().code() != 200) {
            final ByteBuf buf = Unpooled.copiedBuffer((CharSequence)response.status().toString(), CharsetUtil.UTF_8);
            response.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength((HttpMessage)response, (long)response.content().readableBytes());
        }
        final ChannelFuture f = ctx.channel().writeAndFlush((Object)response);
        if (!HttpUtil.isKeepAlive((HttpMessage)response) || response.status().code() != 200) {
            f.addListener((GenericFutureListener)ChannelFutureListener.CLOSE);
        }
    }
    
    public ByteBuf getContent() {
        try (final InputStream in = this.getClass().getResourceAsStream("/index.html")) {
            final byte[] data = new byte[in.available()];
            if (in.read(data) > 0) {
                return Unpooled.wrappedBuffer(data);
            }
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Unpooled.EMPTY_BUFFER;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)WebSocketIndexPageHandler.class);
    }
}
